<?php defined('BASEPATH') OR exit('No direct script access allowed');

class  MY_Controller  extends  CI_Controller  {

    public $em; 
    
    function __construct()
    {
        parent::__construct();
        
        // Instantiate Doctrine's Entity manage and Query builder so we don't have to everytime we want to use Doctrine
        $this->em = $this->doctrine->em;
        $this->qb = $this->em->createQueryBuilder();
        
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters($this->_get_error_ldelim(), $this->_get_error_rdelim());
        
        $revision = $this->session->userdata('revision');
        
        if($revision == false)
        {
        	$info = $this->_getSVNRevision();
        	
        	if (isset($info['checkout-rev']))
        	{
        		$revision = $info['checkout-rev'];
        		$this->session->set_userdata('revision', $revision);
        	}
        }
        $this->smarty->assign('revision', $revision);
        
        if (ENVIRONMENT != 'development')
        {
        	$this->smarty->assign('social_enabled', true);
        	$this->smarty->assign('plus_this', '<g:plusone size="tall"></g:plusone>');
        	$this->smarty->assign('tweet_this', '<a href="http://twitter.com/share" class="twitter-share-button" data-count="vertical" data-via="upcmandaue">Tweet</a>');
        }
        else
        {
        	$this->smarty->assign("evd", 'evd/');
        }
        
        // Check if user logged in.
        if ($this->tank_auth->is_logged_in())
        {
        	$this->smarty->assign('is_logged_in', true);
        	$this->smarty->assign('user_id', $this->tank_auth->get_user_id());
			$this->smarty->assign('user_login', $this->tank_auth->get_username());
        }
        else
        {
        	$data['is_logged_in'] = false;
        }
        
        // Create Navigation Links
        $_navlink_obj = new \models\Navlink;
        $navlinks = $_navlink_obj->createNavlinks();
        $this->smarty->assign('navlinks', $navlinks);
        
        // Create Verse
        $_verse_obj = new \models\Verse;
        $_verse_id  = rand(1, 323);
		$_verse = $_verse_obj->getVerseById($_verse_id);
        $_hits  = $_verse->verse_hits;
        
        // Update Verse hits
        $_verse->verse_hits++;
        $this->em->flush();
        
        $this->smarty->assign('verse_reference', $_verse->verse_reference);
        $this->smarty->assign('verse_text', $_verse->verse_text);
    }
    
    // retrieves the controller's js file if it exists.
    function _get_script($_file)
    {
        $_array = explode(DIRECTORY_SEPARATOR . 'controllers' . DIRECTORY_SEPARATOR, $_file);
        $cnt = count($_array);
        
        if ( strpos($_array[$cnt-1], '.') === false )
		{
            $_array[$cnt-1] .= '.php';
        }
        $script_name = substr($_array[$cnt-1], 0, -4);
        
        if(fopen(FCPATH.'themes/js/evd/' . $script_name . '.js', 'r'))
        {
            $jscript = base_url() . 'themes/js/evd/' . $script_name . '.js';
            $this->smarty->assign('controller_js', $jscript);
        }
        
        if(fopen(FCPATH.'themes/css/evd/' . $script_name . '.css', 'r'))
        {
            $css_file = base_url() . 'themes/css/evd/' . $script_name . '.css';
            $this->smarty->assign('controller_css', $css_file);
        }
    }
    
    function _get_error_ldelim()
    {
        return '<div class="ui-widget" id="error_login" style="">
                <div class="ui-state-error ui-corner-all" style="padding: 0 .7em;">
                    <p>
                        <span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>
                        <strong>Alert:</strong> ';
    }
    
    function _get_error_rdelim()
    {
        return '</p>
                </div>
            </div>';
    }
    
    function _getSVNRevision()
    {
		$entries = BASEPATH.'../.svn/entries';
		if( !file_exists( $entries ) ) {
			return false;
		}
		$lines = file( $entries );
		if ( !count( $lines ) ) {
			return false;
		}
		// check if file is xml (subversion release <= 1.3) or not (subversion release = 1.4)
		if( preg_match( '/^<\?xml/', $lines[0] ) ) {
			// subversion is release <= 1.3
			if( !function_exists( 'simplexml_load_file' ) ) {
				// We could fall back to expat... YUCK
				return false;
			}

			// SimpleXml whines about the xmlns...
			wfSuppressWarnings();
			$xml = simplexml_load_file( $entries );
			wfRestoreWarnings();

			if( $xml ) {
				foreach( $xml->entry as $entry ) {
					if( $xml->entry[0]['name'] == '' ) {
						// The directory entry should always have a revision marker.
						if( $entry['revision'] ) {
							return array( 'checkout-rev' => intval( $entry['revision'] ) );
						}
					}
				}
			}

			return false;
		}


		// Subversion is release 1.4 or above.
		if ( count( $lines ) < 11 ) {
			return false;
		}

		$info = array(
			'checkout-rev' => intval( trim( $lines[3] ) ),
			'url' => trim( $lines[4] ),
			'repo-url' => trim( $lines[5] ),
			'directory-rev' => intval( trim( $lines[10] ) )
		);
		
		return $info;
    }
    
    public function _urlSafe($str)
    {
    	$str = strtolower( trim( strip_tags( $str ) ) );
        $str = preg_replace('/[^a-z0-9-]/', '-', $str);
        $str = preg_replace('/-+/', "-", $str);
        
        return $str;
    }
}